package com.example.administrator.design.ui.login.presenter;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.design.base.mvpbase.baseImpl.BasePresenterImpl;
import com.example.administrator.design.retroft.Api;
import com.example.administrator.design.retroft.ExceptionHelper;
import com.example.administrator.design.ui.login.contact.RegisterContact;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class RegisterPresenter extends BasePresenterImpl<RegisterContact.RegisterView>
        implements RegisterContact.RegisterPresenter {

    public RegisterPresenter(RegisterContact.RegisterView view) {
        super(view);
    }

    @SuppressLint("CheckResult")
    @Override
    public void register() {
        String userId = view.getUserName();
        String phone = view.getPhone();
        String psd = view.getPsd();
        String submitPsd = view.getSubmitPsd();
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(phone) ||
                TextUtils.isEmpty(psd) || TextUtils.isEmpty(submitPsd)) {
            ToastUtils.showShort("nput can not be empty");
        } else if (!psd.equals(submitPsd)) {
            ToastUtils.showShort("Two cipher inconsistencies");
        } else {
            Api.getInstance().register(phone, psd, userId)
                    .subscribeOn(Schedulers.io())
                    .doOnSubscribe(disposable -> {
                        addDisposable(disposable);
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(storiesBeen -> {
                        //处理服务器返回的数据
                        if (storiesBeen.getCode().equals("0")) {
                            ToastUtils.showShort(storiesBeen.getMsg());
                            view.success(storiesBeen);
                            //处理服务器返回的错误信息
                        } else {
                            Log.e("Throwable", storiesBeen.getMsg());
                            ToastUtils.showShort(storiesBeen.getMsg());
                        }
                        //处理网络异常
                    }, ExceptionHelper::handleException);
        }
    }
}
